package com.example.niuke.controller;

import com.example.niuke.annotation.LoginRequired;
import com.example.niuke.entity.User;
import com.example.niuke.service.FollowService;
import com.example.niuke.service.LikeService;
import com.example.niuke.service.UserService;
import com.example.niuke.util.CommunityConstant;
import com.example.niuke.util.CommunityUtil;
import com.example.niuke.util.HostHolder;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.Banner;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;

@Controller
@RequestMapping("/user")
public class UserController  implements CommunityConstant {

    @Value("D:/niuke/upload")
    private String uploadPath;
    @Value("${path.domain}")
    private String domain;
    @Resource
    private UserService userService;
    @Resource
    private HostHolder hostHolder;
    @Resource
    private LikeService likeService;
    @Resource
    private FollowService followService;
    /**
     * 账号设置界面
     * @param model
     * @return
     */
    @LoginRequired
    @RequestMapping("/setting")
    public String findById(Model model){

        return "/site/setting";
    }

    /**
     * 上传文件
     * @param headerImage
     * @param model
     * @return
     */
    @LoginRequired
    @PostMapping("/upload")
    public String uploadHeader(MultipartFile headerImage, Model model) {
        if(headerImage == null) {
            model.addAttribute("error", "您还没选择图片");
            return "/site/setting";
        }
        String filename = headerImage.getOriginalFilename();
        String suffix = filename.substring(filename.lastIndexOf("."));
        if(StringUtils.isBlank(suffix)) {
            model.addAttribute("error", "文件格式不正确");
            return "/site/setting";
        }
        filename = CommunityUtil.generateUUID() + suffix;

        File file = new File(uploadPath + "/" + filename);

        try {
            headerImage.transferTo(file);
        } catch (IOException e) {
            throw new RuntimeException("上传文件失败");
        }
        User user = hostHolder.getUser();
        String url = domain + "/user/header/" + filename;

        userService.updateHeader(user.getId(), url);

        return "redirect:/index";
    }

    /**
     * 映射路由文件与本地文件
     * @param fileName
     * @param response
     */
    @GetMapping("/header/{fileName}")
    public void getHeader(@PathVariable("fileName") String fileName, HttpServletResponse response) {
        fileName = uploadPath + "/" + fileName;
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        response.setContentType("image/ "+ suffix);
        try {
            OutputStream os = response.getOutputStream();
            FileInputStream in = new FileInputStream(fileName);
            byte[] buffer = new byte[1024];
            int b=0;
            while((b = in.read(buffer)) != -1) {
                os.write(buffer, 0, b);
            }
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @GetMapping("/profile/{userId}")
    public String getProfilePage(@PathVariable("userId") int userId, Model model) {
        User user = userService.findUserById(userId);
        if (user == null) {
            throw new RuntimeException("该用户不存在");
        }

        //用户的基本信息
        model.addAttribute("user", user);
        //用户被点赞数量
        int userLikeCount = likeService.findUserLikeCount(userId);
        model.addAttribute("likeCount", userLikeCount);
        //关注数量
        long followeeCount = followService.findFolloweeCount(userId, ENTITY_TYPE_USER);
        model.addAttribute("followeeCount",followeeCount);
        //粉丝数量
        long followerCount = followService.findFollowerCount(ENTITY_TYPE_USER, userId);
        model.addAttribute("followerCount",followerCount);
        //是否已关注
        boolean hasFollowed = false;
        if (hostHolder.getUser() != null) {
            hasFollowed = followService.hasFollowed(hostHolder.getUser().getId(), ENTITY_TYPE_USER, userId);
        }
        model.addAttribute("hasFollowed", hasFollowed);
        return "/site/profile";
    }

}
